<template>
  <el-upload
    ref="uploadRef"
    :limit="1"
    :show-file-list="false"
    :accept="imageType.concat(',').toString()"
    :http-request="uploadChange"
    :before-upload="beforeUpload"
    :on-success="uploadSuccess"
    :on-errors="uploadErrors"
    :disabled="!upload"
    @click.stop=""
  >
    <template #default>
      <el-image
        class="image-radius"
        :style="{ width, height }"
        :src="modelValue"
        fit="cover"
        :preview-src-list="upload ? [] : [modelValue as string]"
        preview-teleported
        lazy
      >
        <template #error>
          <div class="image-slot image-radius">
            <el-icon><icon-picture /></el-icon>
          </div>
        </template>
      </el-image>
    </template>
    <template #tip>
      <div v-if="upload">
        <el-text type="primary">
          点击封面上传，仅支持上传png/jpeg/webp/bmp/gif格式且大小不能超过5MB。
        </el-text>
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import UserAPI, { type User } from "@/api/user";
import {
  UploadRequestOptions,
  UploadRawFile,
  UploadInstance,
} from "element-plus";
import { Picture as IconPicture } from "@element-plus/icons-vue";

defineOptions({
  name: "ArticleCover",
});

const props = defineProps({
  modelValue: {
    type: String,
  },
  width: {
    type: String,
    default: "100%", //220px
  },
  height: {
    type: String,
    default: "100%", //150px
  },
  upload: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue"]);

const imageType = [
  "image/png",
  "image/jpeg",
  "image/webp",
  "image/bmp",
  "image/gif",
];
const uploadRef = ref<UploadInstance>();
const uploadChange = ({ file }: UploadRequestOptions) => {
  return UserAPI.upload(file);
};
const beforeUpload = (rawFile: UploadRawFile) => {
  const isImageSize = rawFile.size / 1024 / 1024 < 5;
  const isImageType = imageType.includes(rawFile.type);
  if (!isImageType) {
    ElMessage.info("您上传的文件不是图片");
  } else if (!isImageSize) {
    ElMessage.info("图片大小不能超过5MB");
  }
  return isImageSize && isImageType;
};
const uploadSuccess = (response: string) => {
  emit("update:modelValue", response);
  uploadRef.value?.clearFiles();
  ElMessage.success("上传文章封面成功");
};
const uploadErrors = (error: Error) => {
  ElMessage.error("上传失败," + error);
};
</script>

<style lang="scss" scoped>
.image-radius {
  border-radius: 6px;
}

@media (width <= 767px) {
  .image-radius {
    display: block;
    width: 110px !important;
    height: 75px !important;
  }
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 30px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
}

.image-slot .el-icon {
  font-size: 30px;
}
</style>
<style>
.el-upload {
  display: inline;
}
</style>
